package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constant.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 购物车数据结构 <key, <hashKey, Cart>>
     * @param cart
     */
    public void addCart(Cart cart) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车对象的key值
        String key = LyConstants.USER_CART_KEY_PRE+userId;
        //通过key值获取当前用户的购物车hash
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(key);
        //获取当前要添加的新的购物车的hashKey
        String hashKey = cart.getSkuId().toString();
        //判断当前新添加的购物车是否已经存在于之前的hash中
        if(hashCart.hasKey(hashKey)){
            //得到对应的购物车对象
            String oldCartStr = hashCart.get(hashKey);
            //将字符串转成Cart对象
            Cart oldCart = JsonUtils.toBean(oldCartStr, Cart.class);
            //如果包含直接将hashKey对应的Cart对象的数量相加
            cart.setNum(cart.getNum()+oldCart.getNum());
        }
        //保存购物车
        hashCart.put(hashKey, JsonUtils.toString(cart));
    }

    public List<Cart> findCarts() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //得到当前用户在redis中的购物车对象的key值
        String key = LyConstants.USER_CART_KEY_PRE+userId;
        //通过key值获取当前用户的购物车hash
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(key);
        //查看是否有购物车
        if(hashCart==null || hashCart.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //获取所有的购物车对象
        List<String> cartsStr = hashCart.values();
        //将字符串类型购物车集合转成对象类型
        List<Cart> carts = cartsStr.stream().map(cart -> JsonUtils.toBean(cart, Cart.class)).collect(Collectors.toList());
        return carts;
    }

    public void addCarts(List<Cart> carts) {
        for (Cart cart : carts) {
            addCart(cart);
        }
    }

}
